<html>
<head>
    <title>SSE(Server-Sent Events) Chat</title>
    <style>
        span {
            display: inline
        }

        input {
            display: inline
        }
    </style>
</head>
<body>
<!-- The chat UI is just a single text input field -->
<!-- New chat messages will be inserted before this input field -->
<div id="chatDiv">
    <span id="nickName"></span>
    <input id="input" style="width:80%; padding:10px; border:solid black 2px" value="谁不是错过了四下报更的鼓声，总有人偷偷拨弄镜月的指针"/>
</div>

<script>
    // Take care of some UI details
    let nick = prompt("Enter your nickname");     // Get user's nickname
    let input = document.getElementById("input"); // Find the input field
    input.focus();                                // Set keyboard focus

    let nickName = document.getElementById("nickName");
    nickName.textContent = nick + ': '

    let chatDiv = document.getElementById("chatDiv");

    // Register for notification of new messages using EventSource
    let chat = new EventSource("/chat");

    class SSE {
        #div

        constructor() {
            this.createDiv()
            chat.addEventListener('chatEventXX', this.append)
        }

        createDiv() {
            this.#div = document.createElement("div");
            chatDiv.before(this.#div);
            chatDiv.scrollIntoView();
        }

        append = (event) => {
            if (event.data === '☺') {
                this.createDiv()
                return
            }
            // console.log(event.data.length)
            this.#div.append(event.data);

            if (event.data === 'Connected')
                this.createDiv()
        }
    }
    new SSE()

    // Post the user's messages to the server using fetch
    input.addEventListener("change", () => {  // When the user strikes return
        fetch("/chat", {                    // Start an HTTP request to this url.
            method: "POST",                 // Make it a POST request with body
            body: nick + ": " + input.value // set to the user's nick and input.
        }).catch(e => console.error);         // Ignore response, but log any errors.
        input.value = "";                   // Clear the input
    });
</script>
</body>
</html>
